from ..bot_plugin import Bot_plugin
from .kuaiji_bot.kuaiji import Kuaiji
from cqhttp import CQHttp
from bot_body import Bot_body
from tools.CQ_tools import img_url_to_CQCode
from tools.CQ_tools import group_msg_level
import logging
import colorful
import time

class Plugin_kuaiji(Bot_plugin):
    def __init__(self, bot_body: Bot_body, name="Kuaiji Bot"):
        Bot_plugin.__init__(self, bot_body, name=name)
        self.help_msg = r"""【刷题会计助手帮助】
0. 刷题会计帮助： 显示本条信息
1. 刷题会计开始 username password: 设置账号密码并启动刷题助手(暂不支持含空格的账户名和密码)
"""

    def handle_msg(self, context):
        bot = self.bot
        msg_level = group_msg_level.judge(context, master_qqs=self.master_qqs)
        raw_message = context['raw_message']
        if raw_message == '刷题会计帮助' and msg_level >= group_msg_level.MEMBER:
            bot.send(context, self.help_msg)
            return 
        if raw_message[:6] == '刷题会计开始' and msg_level >= group_msg_level.MEMBER:
            pattern = r'刷题会计开始 (?P<username>.*?) (?P<password>.*)'
            import re
            ret = re.match(pattern, raw_message)
            if ret == None:
                bot.send(context, self.help_msg)
                return
            d = ret.groupdict()
            username = d['username']
            password = d['password']
            reply_msg = '账号:{}\n密码:{}\n准备启动刷题'.format(username, password)
            bot.send(context, reply_msg)
            # qidong
            def launch_kuaiji(username, password):
                qq_send = lambda msg: bot.send(context, msg)
                kuaiji = Kuaiji(username=username, password=password, browser_type='chrome', qq_send=qq_send)
                kuaiji.run()
            import threading
            t = threading.Thread(target=launch_kuaiji, args=(username, password))
            t.setDaemon(True)
            t.start()
            return



